<template>
  <div class="coupon-template-management">
    <div class="page-header">
      <h1>优惠券模板管理</h1>
      <p>管理系统中的优惠券模板，包括满减券和折扣券</p>
    </div>

    <!-- 操作区域 -->
    <div class="operation-bar">
      <div class="search-area">
        <el-input
          v-model="searchForm.name"
          placeholder="请输入优惠券名称搜索"
          style="width: 300px"
          clearable
          @keyup.enter="handleSearch"
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-button type="primary" @click="handleSearch" :loading="loading">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
      </div>

      <div class="action-area">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增优惠券模板
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        :loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column prop="name" label="模板名称" min-width="150" />

        <el-table-column prop="type" label="类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.type === 'fixed' ? 'primary' : 'success'" size="small">
              {{ row.type === 'fixed' ? '满减券' : '折扣券' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="value" label="面值/折扣" width="120" align="center">
          <template #default="{ row }">
            <span v-if="row.type === 'fixed'" class="value-text">
              {{ parseFloat(row.value).toFixed(2) }} 元
            </span>
            <span v-else class="value-text">
              {{ parseFloat(row.value) }} 折
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="min_spend" label="使用门槛" width="120" align="center">
          <template #default="{ row }">
            <span v-if="parseFloat(row.min_spend) > 0">
              满 {{ parseFloat(row.min_spend).toFixed(2) }} 元
            </span>
            <span v-else class="no-limit">无门槛</span>
          </template>
        </el-table-column>

        <el-table-column prop="validity_type" label="有效期规则" width="180">
          <template #default="{ row }">
            <span v-if="row.validity_type === 'fixed_days'">
              领取后 {{ row.valid_days || 30 }} 天内有效
            </span>
            <span v-else>
              {{ formatDateOnly(row.valid_start_date) }} 至 {{ formatDateOnly(row.valid_end_date) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="total_quantity" label="发行总量" width="100" align="center">
          <template #default="{ row }">
            <span v-if="row.total_quantity === -1" class="unlimited">不限量</span>
            <span v-else>{{ row.total_quantity }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="issued_quantity" label="已领取" width="100" align="center" />

        <el-table-column prop="is_active" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="260" fixed="right">
          <template #default="{ row }">
            <el-button type="success" size="small" @click="handleIssueCoupon(row)">
              <el-icon><Present /></el-icon>
              发放
            </el-button>
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        @submit.prevent
      >
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入优惠券名称" />
        </el-form-item>

        <el-form-item label="优惠券类型" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio value="fixed">满减券</el-radio>
            <el-radio value="discount">折扣券</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item :label="valueLabel" prop="value">
          <el-input-number
            v-model="formData.value"
            :min="0.01"
            :max="formData.type === 'discount' ? 10 : 9999"
            :precision="formData.type === 'discount' ? 1 : 2"
            :step="formData.type === 'discount' ? 0.1 : 1"
            style="width: 200px"
          />
          <span class="input-suffix">{{ valueSuffix }}</span>
          <div v-if="formData.type === 'discount'" class="form-tip">
            请输入0.1-10之间的数字，如8.8折请填写8.8
          </div>
        </el-form-item>

        <el-form-item label="最低消费" prop="min_spend">
          <el-input-number
            v-model="formData.min_spend"
            :min="0"
            :max="9999"
            :precision="2"
            style="width: 200px"
          />
          <span class="input-suffix">元</span>
          <div class="form-tip">设置为0表示无门槛</div>
        </el-form-item>

        <el-form-item label="有效期类型" prop="validity_type">
          <el-radio-group v-model="formData.validity_type">
            <el-radio value="fixed_days">固定天数</el-radio>
            <el-radio value="date_range">日期范围</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="formData.validity_type === 'fixed_days'"
          label="有效天数"
          prop="valid_days"
        >
          <el-input-number
            v-model="formData.valid_days"
            :min="1"
            :max="365"
            style="width: 200px"
          />
          <span class="input-suffix">天</span>
          <div class="form-tip">用户领取后N天内有效</div>
        </el-form-item>

        <el-form-item
          v-if="formData.validity_type === 'date_range'"
          label="有效期范围"
          prop="dateRange"
        >
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 300px"
          />
        </el-form-item>

        <el-form-item label="发行总量" prop="total_quantity">
          <el-input-number
            v-model="formData.total_quantity"
            :min="-1"
            :max="999999"
            style="width: 200px"
          />
          <span class="input-suffix">张</span>
          <div class="form-tip">设置为-1表示不限量</div>
        </el-form-item>

        <el-form-item label="是否启用" prop="is_active">
          <el-switch v-model="formData.is_active" />
          <div class="form-tip">禁用后用户无法领取此优惠券</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            {{ submitLoading ? '提交中...' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 发放优惠券对话框 -->
    <el-dialog
      v-model="issueDialogVisible"
      title="发放优惠券"
      width="500px"
      :close-on-click-modal="false"
      @close="handleIssueDialogClose"
    >
      <div class="issue-coupon-content">
        <div class="template-info">
          <h4>优惠券模板信息</h4>
          <p><strong>名称：</strong>{{ currentTemplate?.name }}</p>
          <p><strong>类型：</strong>{{ currentTemplate?.type === 'fixed' ? '满减券' : '折扣券' }}</p>
          <p><strong>面值：</strong>{{ formatTemplateValue(currentTemplate) }}</p>
          <p><strong>最低消费：</strong>{{ currentTemplate?.min_spend || 0 }}元</p>
        </div>

        <el-divider />

        <div class="user-selection">
          <h4>选择用户</h4>
          <el-input
            v-model="userSearchKeyword"
            placeholder="请输入用户昵称或手机号搜索"
            clearable
            @input="handleUserSearch"
            @clear="handleUserSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <div class="user-list" v-if="userSearchResults.length > 0">
            <div
              v-for="user in userSearchResults"
              :key="user.id"
              class="user-item"
              :class="{ 'selected': selectedUser?.id === user.id }"
              @click="selectUser(user)"
            >
              <div class="user-info">
                <span class="user-name">{{ user.nickname || '未设置昵称' }}</span>
                <span class="user-phone">{{ user.phone_number }}</span>
              </div>
              <div class="user-id">ID: {{ user.id }}</div>
            </div>
          </div>

          <div v-if="userSearchKeyword && userSearchResults.length === 0" class="no-users">
            未找到匹配的用户
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="issueDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="issueLoading"
            :disabled="!selectedUser"
            @click="handleConfirmIssue"
          >
            {{ issueLoading ? '发放中...' : '确认发放' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete, Present } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import {
  getCouponTemplates,
  createCouponTemplate,
  updateCouponTemplate,
  deleteCouponTemplate,
  type CouponTemplate,
  type CreateCouponTemplateParams,
  type UpdateCouponTemplateParams
} from '@/api/coupon'
import { searchUsers, issueCouponToUser, type User } from '@/api/admin'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref<CouponTemplate[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentEditId = ref<number | null>(null)
const formRef = ref<FormInstance>()

// 发放优惠券相关数据
const issueDialogVisible = ref(false)
const issueLoading = ref(false)
const currentTemplate = ref<CouponTemplate | null>(null)
const userSearchKeyword = ref('')
const userSearchResults = ref<User[]>([])
const selectedUser = ref<User | null>(null)

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  name: '',
  type: 'fixed' as 'fixed' | 'discount',
  value: 0,
  min_spend: 0,
  validity_type: 'fixed_days' as 'fixed_days' | 'date_range',
  valid_days: 30,
  total_quantity: -1,
  is_active: true
})

// 日期范围
const dateRange = ref<[string, string] | null>(null)

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑优惠券模板' : '新增优惠券模板')

const valueLabel = computed(() => {
  return formData.type === 'fixed' ? '优惠金额' : '折扣力度'
})

const valueSuffix = computed(() => {
  return formData.type === 'fixed' ? '元' : '折'
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入优惠券名称', trigger: 'blur' },
    { min: 2, max: 50, message: '优惠券名称长度在2到50个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择优惠券类型', trigger: 'change' }
  ],
  value: [
    { required: true, message: '请输入面值', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('面值必须大于0'))
        } else if (formData.type === 'discount' && value > 10) {
          callback(new Error('折扣券面值不能超过10'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  min_spend: [
    { required: true, message: '请输入最低消费金额', trigger: 'blur' }
  ],
  validity_type: [
    { required: true, message: '请选择有效期类型', trigger: 'change' }
  ],
  valid_days: [
    {
      validator: (rule, value, callback) => {
        if (formData.validity_type === 'fixed_days') {
          if (!value || value <= 0) {
            callback(new Error('请输入有效天数'))
          } else if (value > 365) {
            callback(new Error('有效天数不能超过365天'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  dateRange: [
    {
      validator: (rule, value, callback) => {
        if (formData.validity_type === 'date_range') {
          if (!dateRange.value || dateRange.value.length !== 2) {
            callback(new Error('请选择有效期范围'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  total_quantity: [
    { required: true, message: '请输入发行总量', trigger: 'blur' }
  ]
}

// 格式化日期时间
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化日期（只显示日期部分）
const formatDateOnly = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      name: searchForm.name.trim() || undefined
    }

    const response = await getCouponTemplates(params)
    if (response.success) {
      tableData.value = response.data.list
      pagination.total = response.data.total
    } else {
      ElMessage.error('获取数据失败')
    }
  } catch (error) {
    console.error('获取优惠券模板列表失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  fetchData()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchData()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    type: 'fixed' as 'fixed' | 'discount',
    value: 0,
    min_spend: 0,
    validity_type: 'fixed_days' as 'fixed_days' | 'date_range',
    valid_days: 30,
    total_quantity: -1,
    is_active: true
  })
  dateRange.value = null
  formRef.value?.clearValidate()
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  currentEditId.value = null
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: CouponTemplate) => {
  isEdit.value = true
  currentEditId.value = row.id

  // 填充表单数据
  Object.assign(formData, {
    name: row.name,
    type: row.type,
    value: row.value,
    min_spend: row.min_spend,
    validity_type: row.validity_type,
    valid_days: row.valid_days || 30,
    total_quantity: row.total_quantity,
    is_active: Boolean(row.is_active)
  })

  // 处理日期范围
  if (row.validity_type === 'date_range' && row.valid_start_date && row.valid_end_date) {
    dateRange.value = [row.valid_start_date, row.valid_end_date]
  } else {
    dateRange.value = null
  }

  dialogVisible.value = true
}

// 对话框关闭
const handleDialogClose = () => {
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    submitLoading.value = true

    // 构建提交数据
    const submitData: CreateCouponTemplateParams | UpdateCouponTemplateParams = {
      name: formData.name.trim(),
      type: formData.type,
      value: formData.value,
      min_spend: formData.min_spend,
      validity_type: formData.validity_type,
      total_quantity: formData.total_quantity,
      is_active: formData.is_active
    }

    // 根据有效期类型添加相应字段
    if (formData.validity_type === 'fixed_days') {
      submitData.valid_days = formData.valid_days
    } else if (formData.validity_type === 'date_range' && dateRange.value) {
      submitData.valid_start_date = dateRange.value[0]
      submitData.valid_end_date = dateRange.value[1]
    }

    let response
    if (isEdit.value && currentEditId.value) {
      response = await updateCouponTemplate(currentEditId.value, submitData)
    } else {
      response = await createCouponTemplate(submitData as CreateCouponTemplateParams)
    }

    if (response.success) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      fetchData()
    } else {
      ElMessage.error(response.message || (isEdit.value ? '更新失败' : '创建失败'))
    }
  } catch (error: any) {
    if (error !== 'validation failed') {
      console.error('提交优惠券模板失败:', error)
      ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
    }
  } finally {
    submitLoading.value = false
  }
}

// 删除
const handleDelete = async (row: CouponTemplate) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除优惠券模板"${row.name}"吗？删除后相关的用户优惠券也会被删除，此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await deleteCouponTemplate(row.id)
    if (response.success) {
      ElMessage.success('删除成功')
      fetchData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除优惠券模板失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// ==================== 发放优惠券相关方法 ====================

/**
 * 打开发放优惠券对话框
 */
const handleIssueCoupon = (template: CouponTemplate) => {
  currentTemplate.value = template
  issueDialogVisible.value = true
  userSearchKeyword.value = ''
  userSearchResults.value = []
  selectedUser.value = null
}

/**
 * 关闭发放优惠券对话框
 */
const handleIssueDialogClose = () => {
  currentTemplate.value = null
  userSearchKeyword.value = ''
  userSearchResults.value = []
  selectedUser.value = null
}

/**
 * 搜索用户
 */
const handleUserSearch = async () => {
  const keyword = userSearchKeyword.value.trim()

  if (!keyword) {
    userSearchResults.value = []
    return
  }

  if (keyword.length < 2) {
    return
  }

  try {
    const response = await searchUsers(keyword)
    if (response.success) {
      userSearchResults.value = response.data
    } else {
      userSearchResults.value = []
      ElMessage.error('搜索用户失败')
    }
  } catch (error) {
    console.error('搜索用户错误:', error)
    userSearchResults.value = []
    ElMessage.error('搜索用户失败')
  }
}

/**
 * 选择用户
 */
const selectUser = (user: User) => {
  selectedUser.value = user
}

/**
 * 确认发放优惠券
 */
const handleConfirmIssue = async () => {
  if (!currentTemplate.value || !selectedUser.value) {
    ElMessage.error('请选择用户')
    return
  }

  try {
    issueLoading.value = true

    const response = await issueCouponToUser({
      template_id: currentTemplate.value.id,
      user_id: selectedUser.value.id
    })

    if (response.success) {
      ElMessage.success(`优惠券发放成功！已发放给用户：${response.data.user_nickname}`)
      issueDialogVisible.value = false
      fetchData() // 刷新列表以更新已发放数量
    } else {
      ElMessage.error(response.message || '发放失败')
    }
  } catch (error) {
    console.error('发放优惠券错误:', error)
    ElMessage.error('发放失败，请稍后重试')
  } finally {
    issueLoading.value = false
  }
}

/**
 * 格式化模板面值显示
 */
const formatTemplateValue = (template: CouponTemplate | null) => {
  if (!template) return ''

  if (template.type === 'fixed') {
    return `${template.value}元`
  } else {
    return `${template.value}折`
  }
}

// 初始化
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.coupon-template-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-area {
  display: flex;
  gap: 12px;
  align-items: center;
}

.action-area {
  display: flex;
  gap: 12px;
}

.table-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.value-text {
  font-weight: 600;
  color: #e6a23c;
}

.no-limit {
  color: #909399;
  font-size: 12px;
}

.unlimited {
  color: #67c23a;
  font-weight: 600;
}

.input-suffix {
  margin-left: 8px;
  color: #909399;
  font-size: 14px;
}

.form-tip {
  margin-top: 4px;
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
}

/* 发放优惠券对话框样式 */
.issue-coupon-content {
  max-height: 500px;
  overflow-y: auto;
}

.template-info {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 16px;
}

.template-info h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.template-info p {
  margin: 8px 0;
  color: #606266;
  font-size: 14px;
}

.user-selection h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.user-list {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-top: 12px;
}

.user-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.user-item:last-child {
  border-bottom: none;
}

.user-item:hover {
  background-color: #f5f7fa;
}

.user-item.selected {
  background-color: #ecf5ff;
  border-color: #409eff;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-name {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.user-phone {
  color: #909399;
  font-size: 12px;
}

.user-id {
  color: #909399;
  font-size: 12px;
}

.no-users {
  text-align: center;
  padding: 20px;
  color: #909399;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
